#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QFileDialog>
#include<qdebug.h>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //ui
    this->setWindowTitle("视频混剪byTMF");
    //默认输出路径
    //QString dirstr="../默认输出视频保存位置";//不要用相对路径
    QString dirstr=QCoreApplication::applicationDirPath()+"/"+"默认输出视频保存位置";//绝对路径
    QDir dir(dirstr);
    if(dir.exists()==false)
        dir.mkpath(dirstr);
    outfilepath=dirstr;
    ui->label_outpath->setText("输出路径:"+outfilepath);

    //默认
    timezimu=QTime(0,0,0);
    timezimu=timezimu.addSecs(2);

    timefenduan=QTime(0,0,0);
    timefenduan=timefenduan.addSecs(4);

    timelastvideo=QTime(0,0,0);
    timelastvideo=timelastvideo.addSecs(120);

    //菜单
    connect(ui->actionadd_files,&QAction::triggered,[=](){

        QStringList files = QFileDialog::getOpenFileNames(
                                this,
                                "选择视频",
                                "C:/",
                                "video (*.*)");

        for(int i= 0;i<files.count();i++)
        ui->textBrowser->appendPlainText(QString("视频 : %1").arg(files[i]));

        filelist=files;

    });
    connect(ui->actionadd_audiofiles,&QAction::triggered,[=](){

        QStringList files = QFileDialog::getOpenFileNames(
                                this,
                                "选择音频",
                                "C:/",
                                "audio (*.*)");

        for(int i= 0;i<files.count();i++)
        ui->textBrowser->appendPlainText(QString("音频 : %1").arg(files[i]));
        audio_filelist=files;

    });

    connect(ui->actionadd_subtitles_files,&QAction::triggered,[=](){

        QString files = QFileDialog::getOpenFileName(
                                this,
                                "选择字幕",
                                "C:/",
                                "subtitles (*.*)");

        ui->textBrowser->appendPlainText(QString("字幕 : %1").arg(files));
        subtitles=files;

    });
    connect(ui->actionoutfilepath,&QAction::triggered,[=](){outfilepath=QFileDialog::getExistingDirectory(this,"选择保存路径",outfilepath);
    ui->textBrowser->appendPlainText(QString("输出路径 : %1").arg(outfilepath));
    ui->label_outpath->setText("输出路径:"+outfilepath);
    });

}

MainWindow::~MainWindow()
{
    delete ui;

}

void MainWindow::getinfo_befroestart()
{

    //时间
    timezimu=ui->timeEdit_zimu->time();
    timecutstart=ui->timeEdit_cutstart->time();
    timecutend=ui->timeEdit_cutend->time();
    timefenduan=ui->timeEdit_fenduan->time();
    timelastvideo=ui->timeEdit_lastvideo->time();

    //文件
    title=ui->plainTextEdit_title->toPlainText();
    logo=ui->plainTextEdit_logo->toPlainText();

    //文本转字幕
    if(textTOzimu==true)
    {
        //1
        //subtitles = textTOsubtitle(ui->plainTextEdit_makezimu->toPlainText(),timezimu);
        //qDebug()<<ui->plainTextEdit_makezimu->toPlainText();
        //2
        subtitles=textTOsubtilte_fuhao(ui->plainTextEdit_makezimu->toPlainText().toUtf8(),timezimu);
    }

    //配置信息
    //QString dirstr=QCoreApplication::applicationDirPath()+"/"+"默认输出视频保存位置";//绝对路径
    QString setpath= QCoreApplication::applicationDirPath()+"/"+"data";//绝对路径
    QDir dir (setpath);
    if(dir.exists()==false)
        dir.mkpath(setpath);
    QString infoname=setpath+"/"+"配置信息.txt";
    QFile file(infoname);
    if(file.open(QIODevice::WriteOnly))
    {
        QString argu;
        //剪切
        QString strcutbegin_end;
        if(cut_startend==true)
            strcutbegin_end="y";
        else {
            strcutbegin_end="n";
        }
        //0 1
        argu.append("是否裁剪开头结尾:");argu.append(QString("{%1}").arg(strcutbegin_end));
        //2 3
        argu.append("裁剪时间(开头):");argu.append(QString("{%1}").arg(timecutstart.hour()*60*60+timecutstart.minute()*60+timecutstart.second()));
        //4 5
        argu.append("裁剪时间(结尾):");argu.append(QString("{%1}").arg(timecutend.hour()*60*60+timecutend.minute()*60+timecutend.second()));
        //只剪切开头结尾
        QString onlycut;
        if(onlycut_beginend)
        {
            onlycut="y";
        }
        else {
            onlycut="n";
        }
        //6 7
        argu.append("只开启剪切功能:");argu.append(QString("{%1}").arg(onlycut));

        //setlogo
        QString issetlogo;
        if(setlogo==true)
        {
            issetlogo="y";
        }
        else {
            issetlogo="n";
        }
        //8 9
        argu.append("是否设置logo:");argu.append(QString("{%1}").arg(issetlogo));
        //10 11
        argu.append("logo大小:");argu.append(QString("{%1}").arg(ui->spinBox_fontsize->value()));
        //12 13
        argu.append("logo_x:");argu.append(QString("{%1}").arg(ui->spinBox_logox->value()));
        //14 15
        argu.append("logo_y:");argu.append(QString("{%1}").arg(ui->spinBox_logoy->value()));

        //setvideo
        QString issetvideo;
        if(setvideo==true)
            issetvideo="y";
        else
        {
            issetvideo="n";
        }
        //16 17
        argu.append("是否设置video:");argu.append(QString("{%1}").arg(issetvideo));
        //18 19
        argu.append("视频码率:");argu.append(QString("{%1}").arg(ui->spinBox_videobt->value()));
        //20 21
        argu.append("分辨率w:");argu.append(QString("{%1}").arg(ui->spinBox_video_w->value()));
        //22 23
        argu.append("分辨率h:");argu.append(QString("{%1}").arg(ui->spinBox_video_h->value()));

        //画面裁剪

        QString pictruecut;
        if(piccut)
            pictruecut="y";
        else {
            pictruecut="n";
        }
        //24 25
        argu.append("画面裁剪:");argu.append(QString("{%1}").arg(pictruecut));
        //26 27
        argu.append("宽度:");argu.append(QString("{%1}").arg(ui->spinBox_piccutw->value()));
        //28 29
        argu.append("高度:");argu.append(QString("{%1}").arg(ui->spinBox_piccuth->value()));
        //30 31
        argu.append("坐标x:");argu.append(QString("{%1}").arg(ui->spinBox_piccutx->value()));
        //31 33
        argu.append("坐标y:");argu.append(QString("{%1}").arg(ui->spinBox_piccuty->value()));

        file.write(argu.toUtf8());
        file.close();
    }

}

QString MainWindow::textTOsubtitle(QString text,QTime time)
{
    /*
0
00:00:02,080 --> 00:00:05,040
College English test band 4
大学英语四级考试

1
00:00:05,370 --> 00:00:13,540
part 2 listening comprehension section a directions in this section
第二部分听力理解a部分本部分的说明
*/
    QStringList strlist;
    text=text.toUtf8();
    text=text.replace("\n","");
    //qDebug()<<text;

    int strnum=40;
    int strsum=text.length();
    int num=strsum/strnum;
    int yushu=strsum%strnum;

    int chushu;
    if(yushu==0)
    {
        chushu=num;
    }
    else {
        chushu=num+1;
    }

    for(int i=0,j=0;i<chushu;i++)
    {
        QString str=text.mid(j,strnum);//j+strnum mid第二个参数是往后的长度
        strlist.append(str);
        j+=strnum;
        qDebug()<<"str="<<str;
    }

    QString subtilename=outfilepath+"/"+"文本转字幕.srt";
    DeleteFileOrFolder(subtilename);

    QFile file(subtilename);
    if(file.open(QIODevice::ReadWrite))
    {
        QTime subtime(0,0,0);
        for(int i=0;i<strlist.count();i++)
        {
            file.write(QString::number(i).toUtf8().data());file.write("\n");

            file.write(subtime.toString("hh:mm:ss,sss").toUtf8());file.write(" --> ");
            int sce=time.hour()*60*60+time.minute()*60+time.second();
            subtime= subtime.addSecs(sce);
            file.write(subtime.toString("hh:mm:ss,sss").toUtf8());file.write("\n");

            file.write(strlist[i].toUtf8().data());file.write("\n");

             file.write("\n");
        }

        file.close();
    }

    return subtilename;
}

QString MainWindow::textTOsubtilte_fuhao(QString text, QTime time)
{
    QStringList strlist;
    text=text.toUtf8();
    //断掉的友情......
    text=text.replace("......",".");
    text=text.replace("...",".");
    text=text.replace(".....",".");
    text=text.remove(" ");
    text=text.remove(" ");
    text=text.remove("\n");

    //qDebug()<<text;
    strlist=text.split(QRegExp("[,.，。：:”!！；;?？]"));
    QString subtilename=outfilepath+"/"+"文本转字幕.srt";
    DeleteFileOrFolder(subtilename);

    QFile file(subtilename);
    DeleteFileOrFolder(subtilename);

    if(file.open(QIODevice::ReadWrite))
    {
        QTime subtime(0,0,0);
        int biaoshi=strlist.count();
        for(int i=0;i<biaoshi;i++)
        {

            file.write(QString::number(i).toUtf8());file.write("\n");

            file.write(subtime.toString("hh:mm:ss,sss").toUtf8());file.write(" --> ");
            int sce=time.hour()*60*60+time.minute()*60+time.second();
            subtime= subtime.addSecs(sce);
            file.write(subtime.toString("hh:mm:ss,sss").toUtf8());file.write("\n");

            file.write(strlist[i].toUtf8());file.write("\n");

            file.write("\n");
        }

        file.close();
    }

    return subtilename;

}


void MainWindow::on_pushButton_start_clicked()
{

   getinfo_befroestart();

   bool addaudio=0,addzimu=0;
   if(audio_filelist.isEmpty()==false)
       addaudio=true;
   if(subtitles.isEmpty()==false)
       addzimu=true;

   //判断
   if(filelist.isEmpty()||outfilepath.isEmpty())
   {
       ui->textBrowser->appendPlainText("未选择视频或者未设置输出路径");
       return;
   }
   if(timefenduan.toString("hh:mm:ss")=="00:00:00"||timelastvideo.toString("hh:mm:ss")=="00:00:00")
   {
       ui->textBrowser->appendPlainText("未设置切割时长或最后每一个视频的时长");
       return;
   }
   if(title.isEmpty())
   {
       ui->textBrowser->appendPlainText("请设置视频名称");
       return;
   }

   mythread *mythr=new mythread(NULL);
   connect(mythr,&mythread::signal_info,this,&MainWindow::slot_getinfo);

   connect(mythr,&QThread::finished,mythr,&QObject::deleteLater);

   mythr->setinfo_beforestart(filelist,outfilepath,timefenduan,timelastvideo,audio_filelist,subtitles,title,logo,addaudio,addzimu);
   mythr->start();

   qDebug()<<"void MainWindow::on_pushButton_start_clicked()";


}

void MainWindow::on_pushButton_clicked()
{

    QStringList files = QFileDialog::getOpenFileNames(
                            this,
                            "选择视频",
                            "C:/",
                            "video (*.*)");

    for(int i= 0;i<files.count();i++)
    ui->textBrowser->appendPlainText(QString("视频 : %1").arg(files[i]));

    filelist=files;
}

void MainWindow::on_pushButton_2_clicked()
{
    QStringList files = QFileDialog::getOpenFileNames(
                            this,
                            "选择音频",
                            "C:/",
                            "audio (*.*)");

    for(int i= 0;i<files.count();i++)
    ui->textBrowser->appendPlainText(QString("音频 : %1").arg(files[i]));

    audio_filelist=files;
}

void MainWindow::on_pushButton_3_clicked()
{
    QString files = QFileDialog::getOpenFileName(
                            this,
                            "选择字幕",
                             "C:/",
                            "subtitles (*.*)");

    ui->textBrowser->appendPlainText(QString("字幕 : %1").arg(files));

    subtitles=files;
}

void MainWindow::on_checkBox_textTOzimu_stateChanged(int arg1)
{
    if(ui->checkBox_textTOzimu->isChecked())
    {
        textTOzimu=true;
        return;
    }
    textTOzimu=false;
}

void MainWindow::on_checkBox_cut_startend_stateChanged(int arg1)
{
    if(ui->checkBox_cut_startend->isChecked())
    {
        cut_startend=true;
        return;
    }
    cut_startend=false;

}

void MainWindow::slot_getinfo(QString str, QString pro)
{
    if(str=="视频制作完成...")
    {
        ui->textBrowser->setPlainText(str);
        ui->textBrowser_process->setPlainText(pro);
        return;
    }
    ui->textBrowser->appendPlainText(str);
    ui->textBrowser_process->appendPlainText(pro);
}

void MainWindow::on_pushButton_4_clicked()
{

    //打开文件夹
    QDesktopServices::openUrl(QUrl("file:///" + outfilepath));
}

void MainWindow::on_checkBox_onlycut_beginend_stateChanged(int arg1)
{
    if(ui->checkBox_onlycut_beginend->isChecked())
    {
        onlycut_beginend=true;
        return;
    }
    onlycut_beginend=false;
}

void MainWindow::on_checkBox_setlogo_stateChanged(int arg1)
{
    if(ui->checkBox_setlogo->isChecked())
    {
        setlogo=true;
        return;
    }
    setlogo=false;
}

void MainWindow::on_checkBox_setvideo_stateChanged(int arg1)
{
    if(ui->checkBox_setvideo->isChecked())
    {
        setvideo=true;
        return;
    }
    setvideo=false;
}

void MainWindow::on_pushButton_5_clicked()
{
    QFile file;
    QString filename=textTOsubtilte_fuhao(ui->plainTextEdit_makezimu->toPlainText(),ui->timeEdit_zimu->time());
    file.setFileName(filename);
    file.open(QIODevice::ReadOnly);
    ui->textBrowser->setPlainText(file.readAll());
    file.close();
}

void MainWindow::on_pushButton_7_clicked()
{
    ui->plainTextEdit_makezimu->clear();
}

void MainWindow::on_pushButton_6_clicked()
{
    QString str=ui->plainTextEdit_makezimu->toPlainText();
    str=str.replace("\n","");
    str=str.replace(" ","");
    ui->textBrowser->setPlainText(str);
}

void MainWindow::on_pushButton_8_clicked()
{
    QString str=ui->plainTextEdit_makezimu->toPlainText();
    for(int i=0;i<10;i++)
        str=str.replace(QString("%1").arg(i),"");
    ui->textBrowser->setPlainText(str);
}

void MainWindow::on_pushButton_9_clicked()
{
    QString str=ui->plainTextEdit_makezimu->toPlainText();
    str=str.replace(QString("%1").arg(ui->lineEdit_tihuan_begin->text()),QString("%1").arg(ui->lineEdit_tihuan_after->text()));
    ui->textBrowser->setPlainText(str);
}

bool MainWindow::DeleteFileOrFolder(QString filename)
{
    QString strPath=filename;
    if (strPath.isEmpty() || !QDir().exists(strPath))//是否传入了空的路径||路径是否存在
    {
        qDebug()<<"";
        return false;
    }
    QFileInfo FileInfo(strPath);

    if (FileInfo.isFile())//如果是文件
        QFile::remove(strPath);
    else if (FileInfo.isDir())//如果是文件夹
    {
        QDir qDir(strPath);
        qDir.removeRecursively();
    }
    return true;
}

void MainWindow::on_checkBox_pictruecut_stateChanged(int arg1)
{
    if(ui->checkBox_pictruecut->isChecked())
        piccut=true;
    else {
        piccut=false;
    }

}

void MainWindow::on_pushButton_jiaohuantext_clicked()
{
    QString text1,text2;
    text1=ui->plainTextEdit_makezimu->toPlainText();
    text2=ui->textBrowser->toPlainText();
    ui->plainTextEdit_makezimu->setPlainText(text2);
    ui->textBrowser->setPlainText(text1);
}
